package com.by.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.by.common.conf.CommandMager;
import com.by.common.cont.CommandConst;
import com.by.wx.controller.WxinController;

public class HttpclientUtils {

	public static Log log = LogFactory.getLog(HttpclientUtils.class);

	/**
	 * 根据URL试用get方法取得返回的数据
	 * 
	 * @param url
	 *            URL地址，参数直接挂在URL后面即可
	 * @return
	 */
	public static String getGetDateByUrl(String url) {
		String data = null;
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建GET方法的实例
		GetMethod getMethod = new GetMethod(url);
		// 设置头信息：如果不设置User-Agent可能会报405，导致取不到数据
		getMethod.setRequestHeader(
				CommandMager.getProperty(CommandConst.WX_CONTROL_ROOM_EQUIPMENT_GET_REQUEST_HEADER_ONE),
				CommandMager.getProperty(CommandConst.WX_CONTROL_ROOM_EQUIPMENT_GET_REQUEST_HEADER_PARAM_ONE));
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 开始执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed:" + getMethod.getStatusLine());
				log.error("Method failed:" + getMethod.getStatusLine());
			}
			// 读取内容
			byte[] responseBody = getMethod.getResponseBody();
			// 处理内容
			data = new String(responseBody);
		} catch (HttpException e) {
			// 发生异常，可能是协议不对或者返回的内容有问题
			// System.out.println("Please check your provided http address!");
			log.error("Please check your provided http address!");
			data = "";
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			data = "";
			e.printStackTrace();
		} finally {
			// 释放连接
			getMethod.releaseConnection();
		}
		return data;
	}

	/**
	 * 根据post方法取得返回数据
	 * 
	 * @param url
	 *            URL地址
	 * @param array
	 *            需要以post形式提交的参数
	 * @return
	 */
	public static String getPostDateByUrl(String url, Map<String, String> array) {
		String data = null;
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建post方法的实例
		PostMethod postMethod = new PostMethod(url);
		// 设置头信息
		postMethod.setRequestHeader(
				CommandMager.getProperty(CommandConst.WX_CONTROL_ROOM_EQUIPMENT_POST_REQUEST_HEADER_ONE),
				CommandMager.getProperty(CommandConst.WX_CONTROL_ROOM_EQUIPMENT_POST_REQUEST_HEADER_PARAM_ONE));
		postMethod.addRequestHeader(
				CommandMager.getProperty(CommandConst.WX_CONTROL_ROOM_EQUIPMENT_POST_REQUEST_HEADER_PARAM_TWO),
				CommandMager.getProperty(CommandConst.WX_CONTROL_ROOM_EQUIPMENT_POST_REQUEST_HEADER_PARAM_TWO) + "/"
						+ CommandMager.getProperty(
								CommandConst.WX_CONTROL_ROOM_EQUIPMENT_POST_REQUEST_HEADER_PARAM_APPLICATION)
						+ "=" + CommandMager.getProperty(
								CommandConst.WX_CONTROL_ROOM_EQUIPMENT_POST_REQUEST_HEADER_PARAM_TWO_CHARSET));
		// 遍历设置要提交的参数
		Iterator it = array.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry) it.next();
			String key = entry.getKey();
			String value = entry.getValue().trim();
			postMethod.setParameter(key, value);
		}
		// 使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 执行postMethod
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed:" + postMethod.getStatusLine());
				log.error("Method failed:" + postMethod.getStatusLine());
			}
			// 读取内容
			byte[] responseBody = postMethod.getResponseBody();
			// 处理内容
			data = new String(responseBody);
		} catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			// System.out.println("Please check your provided http address!");
			log.error("Please check your provided http address!");
			data = "";
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			data = "";
			e.printStackTrace();
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}
		// System.out.println(data);
		log.info(data);
		return data;
	}

	/**
	 * 微信获取opennid可能调用此方法，但是该项目没有使用到此方法 ------> get请求 执行url请求数据
	 * 
	 * @param urlStr
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	public static String getUrlData(String urlStr) throws Exception {
		URL url = new URL(urlStr);
		URLConnection connection = url.openConnection();
		// 一旦发送成功，用以下方法就可以得到服务器的回应：
		String sCurrentLine = "";
		StringBuffer sTotalString = new StringBuffer();
		InputStream l_urlStream = connection.getInputStream();
		// 传说中的三层包装阿！
		BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
		while ((sCurrentLine = l_reader.readLine()) != null) {
			sTotalString.append(sCurrentLine);
		}
		return sTotalString.toString();
	}

	/**
	 * 微信获取opennid可能调用此方法，但是该项目没有使用到此方法 ------> post请求 执行url请求数据
	 * 
	 * @param urlStr
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	public static String postUrlData(String urlStr, String data) throws Exception {
		URL url = new URL(urlStr);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setRequestMethod("POST");
		http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		http.setDoOutput(true);
		http.setDoInput(true);
		System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒28
		System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒29
																			// 30
		OutputStream os = http.getOutputStream();
		os.write(data.getBytes("UTF-8"));// 传入参数
		os.flush();
		os.close();
		// 一旦发送成功，用以下方法就可以得到服务器的回应：
		String sCurrentLine = "";
		String sTotalString = "";
		InputStream l_urlStream = http.getInputStream();
		// 传说中的三层包装阿！
		BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
		while ((sCurrentLine = l_reader.readLine()) != null) {
			sTotalString += sCurrentLine;
		}
		return sTotalString;
	}
}
